import { Application } from "@pixi/app";
import { Geometry, Shader, Texture, TYPES } from "@pixi/core";
import { Mesh } from "@pixi/mesh";

let fragmentShader = `
varying vec2 vTextureCoord;
uniform sampler2D uSampler;

void main(void) {
    gl_FragColor = texture2D(uSampler, vTextureCoord);
}
`

// v4的默认顶点着色器
let vertexShader = `
attribute vec2 aVertexPosition;
attribute vec2 aTextureCoord;
uniform mat3 projectionMatrix;
varying vec2 vTextureCoord;

void main(void) {
    gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);
    vTextureCoord = aTextureCoord;
}
`
export async function addMesh(app: Application) {
    let texture = await Texture.fromURL('https://p5.music.126.net/obj/wonDlsKUwrLClGjCm8Kx/23154688063/ec3e/3d4a/7a50/671dfaa933552f588d943ca39375807e.png', {})

    let vertices = new Float32Array([
        -1, -1, 0, 0,
        1, -1, 1, 0,
        1, 1, 1, 1,
        -1, 1, 0, 1
    ]);

    let indices = new Uint16Array([0, 1, 2, 0, 2, 3]);

    let geometry = new Geometry()
        .addAttribute('aVertexPosition', vertices, 2, false, TYPES.FLOAT, 4 * 4, 0)
        .addAttribute('aTextureCoord', vertices, 2, false, TYPES.FLOAT, 4 * 4, 2 * 4)
        .addIndex(indices);

    let shader = Shader.from(vertexShader, fragmentShader, { uSampler: texture });

    let mesh = new Mesh(geometry, shader);

    app.stage.addChild(mesh)
}
